from opt.treesearch import TreeNode
import random


def random_simulation(node, rng=random):
    """Given a TreeNode object (and optionally an RNG), apply randomly selected (with discrete
    uniform distribution) actions/branches to the node until a leaf is reached.
    NOTE: this method operates in-place on the argument 'node'."""
    while not node.is_leaf():
        branches = list(node.branches())
        if len(branches) == 0:
            break
        branch = rng.choice(branches)
        if isinstance(branch, TreeNode):
            node = branch
        else:
            node.apply(branch)
    return node
